package com.kiln.juxingqs.ui.vm

import android.app.Application
import android.net.Uri
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.global.commlib.network.data.JsonResult
import client.global.commlib.network.data.Ret
import client.global.commlib.out_time
import client.global.commlib.toast.toast
import client.global.commlib.utils.StoreUtil
import client.global.commlib.utils.Util
import com.kiln.juxingqs.api.bean.TxJl
import com.kiln.juxingqs.api.bean.UploadRet
import com.kiln.juxingqs.api.bean.UserInfo
import com.kiln.juxingqs.ui.viewmodel.MiddleVm
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response

class PersonInfoViewModel(app: Application) : MiddleVm(app) {
    val isShowing = MutableLiveData<Boolean>(false)
    val userAvatar = MutableLiveData<Uri>()
    val callUser = MutableLiveData<JsonResult<UserInfo>>()
    val callEditName = MutableLiveData<JsonResult<Ret>>()

    val pageOne = MutableLiveData<Int>(0)
    val callOne = MutableLiveData<JsonResult<TxJl>>()

    fun userInfo() {
        hold({
            server.userinfo().apply {
                body()?.let {
                    if (it.isSuccess) {
                        StoreUtil.saveBean(getApplication(), it.data!!)
                    }
                }
            }
        }, success = {
            callUser.value = it
        })
    }

    fun editName(it: String) {
        hold({
            server.reset_nickname(it)
        }, {
            isShowing.value = true
        }, success = {
            callEditName.value = it
        }, complete = {
            isShowing.value = false
        })
    }

    fun setAvatar(lo: LifecycleOwner) {
        if (userAvatar.value == null) {
            toast("请选择图片")
            return
        }
        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<UploadRet>>? = null
                val file = Util.getLuBan(
                    lo,
                    userAvatar.value!!
                )
                val requestFile: RequestBody = RequestBody.create(
                    "multipart/form-data".toMediaTypeOrNull(),
                    file
                )
                val body = MultipartBody.Part.createFormData(
                    "file",
                    file.name,
                    requestFile
                )
                val descriptionString = "file"
                val description = RequestBody.create(
                    "multipart/form-data".toMediaTypeOrNull(),
                    descriptionString
                )
                out_time {
                    val ret = server.upload(description, body)
                    emm = ret
                }
                emit(emm)
            }.map {
                var emm: JsonResult<Ret>? = null
                it?.body()?.let {
                    if (it.isSuccess) {
                        out_time {
                            val ret = server.user_avatar(it.data!!.url)
                            emm = ret?.body()
                        }
                    } else {
                        emm = JsonResult<Ret>().apply {
                            message = it.message
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion { cause ->
                isShowing.value = false
            }.catch { cause ->
                if (cause != null) {
                    toast(cause.message)
                }
            }.collectLatest {
                it?.let {
                    if (it.isSuccess) {
                        toast("设置成功")
                        userInfo()
                    }
                }
            }
        }
    }

}